package cn.uway.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;

import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;


@Configuration
public class RedisConfig {
	protected  Logger logger = LoggerFactory.getLogger(this.getClass());	

	@Value("${redis.host}")
	private String host;
	
	@Value("${redis.port}")
	private int port;
	
	@Value("${redis.dbIndex}")
	private int dbIndex;
	
	@Value("${redis.password}")
	private String password;
	
	@Value("${redis.timeout}")
	private int timeout;
	
	@Value("${redis.pool.maxTotal}")
	private int maxTotal;
	
	@Value("${redis.pool.maxIdle}")
	private int maxIdle;
	
	@Value("${redis.pool.minIdle}")
	private int minIdle;
	
	@Value("${redis.pool.maxWaitMillis}")
	private long maxWaitMillis;		
	
	
	@Bean
    public JedisPoolConfig jedisPoolConfig() {  
		
        JedisPoolConfig poolConfig = new JedisPoolConfig();
		poolConfig.setMaxTotal(maxTotal);
		poolConfig.setMaxIdle(maxIdle);
		poolConfig.setMinIdle(minIdle);	       
		poolConfig.setMaxWaitMillis(maxWaitMillis);
		poolConfig.setTestOnBorrow(true);
		poolConfig.setTestOnReturn(true);
	    return poolConfig;  
    }  
	 
	
	@Bean
	public JedisPool jedisPool() {  
	     return new JedisPool(jedisPoolConfig(), host, port, timeout, password);  
	}  
	      
	
	@Bean
    public JedisConnectionFactory connectionFactory() {
		JedisConnectionFactory factory = new JedisConnectionFactory();
		factory.setHostName(host);
		factory.setPort(port);
		factory.setDatabase(dbIndex);
		factory.setPassword(password);
		factory.setTimeout(timeout);
		
		factory.setUsePool(true);
		factory.setPoolConfig( jedisPoolConfig() );
		 // 初始化连接pool  
		factory.afterPropertiesSet();  		
		
        return  factory;
    }
    
       
	
}
